package com.xm.linxiaogang.base.activity

import android.os.Bundle
import android.os.IBinder
import android.os.PowerManager
import android.os.PowerManager.WakeLock
import android.view.MotionEvent
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import androidx.annotation.IdRes
import androidx.fragment.app.Fragment
import com.example.baselibrary.R

/**
 * 该基类的作用：
 * 1.保持/取消屏幕常亮状态
 * 2.Fragment的添加/替换/显示/隐藏操作
 * 3.在有输入框时，默认收起输入法
 */
abstract class LibBaseActivity : SystemBarActivity() {
    private var pm: PowerManager? = null
    private var wl: WakeLock? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        //管理屏幕常亮状态
        pm = getSystemService(POWER_SERVICE) as PowerManager
        wl = pm!!.newWakeLock(
            PowerManager.FULL_WAKE_LOCK or PowerManager.ACQUIRE_CAUSES_WAKEUP,
            resources.getString(R.string.app_name)
        )
    }

    /**
     * 屏幕常亮
     */
    fun bright() {
        try {
            wl!!.acquire()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 取消常亮
     */
    fun cancelBright() {
        try {
            wl!!.release()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 添加 fragment
     *
     * @param idRes    容器ID
     * @param fragment 待添加的 fragment
     */
    fun addFragment(@IdRes idRes: Int, fragment: Fragment) {
        if (!fragment.isAdded) {
            val ft = supportFragmentManager.beginTransaction()
            ft.add(idRes, fragment)
            ft.commit()
        }
    }

    /**
     * 替换 fragment
     *
     * @param idRes    容器ID
     * @param fragment 待替换的 fragment
     */
    fun replaceFragment(@IdRes idRes: Int, fragment: Fragment) {
        val ft = supportFragmentManager.beginTransaction()
        ft.replace(idRes, fragment)
        ft.commit()
    }

    /**
     * 隐藏 fragment
     *
     * @param fragment
     */
    fun hideFragment(fragment: Fragment) {
        val ft = supportFragmentManager.beginTransaction()
        ft.hide(fragment)
        ft.commit()
    }

    /**
     * 显示 fragment
     *
     * @param fragment
     */
    fun showFragment(fragment: Fragment) {
        val ft = supportFragmentManager.beginTransaction()
        ft.show(fragment)
        ft.commit()
    }

    /**
     * 设置当前Fragment
     *
     * @param id
     * @param fragment
     */
    fun setCurrentFragment(id: Int, fragment: Fragment) {
        val fragments = supportFragmentManager.fragments
        val fragmentTransaction = supportFragmentManager.beginTransaction()
        if (!fragment.isAdded) fragmentTransaction.add(id, fragment, fragment.toString())
        for (i in fragments.indices) {
            val f = fragments[i]
            if (f.tag != fragment.id.toString() + "") fragmentTransaction.hide(f)
        }
        fragmentTransaction.show(fragment)
        fragmentTransaction.commitAllowingStateLoss()
        supportFragmentManager.executePendingTransactions()
    }

    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        if (ev.action == MotionEvent.ACTION_DOWN) {
            val view = currentFocus //当前获取焦点的控件(有输入框的页面焦点默认会被输入框优先占据)
            if (isShouldHideKeyboard(view, ev)) { //判断用户点击的是否是输入框以外的区域
                hideKeyboard(view!!.windowToken) //收起键盘
            }
        }
        return super.dispatchTouchEvent(ev)
    }

    /**
     * 是否需要收起输入法
     *
     * @param view
     * @param event
     * @return
     */
    private fun isShouldHideKeyboard(view: View?, event: MotionEvent): Boolean {
        if (view != null && view is EditText) { //判断得到的焦点控件是否是输入框
            val l = intArrayOf(0, 0)
            view.getLocationInWindow(l)
            //得到输入框在屏幕中的位置
            val left = l[0]
            val top = l[1]
            val bottom = top + view.getHeight()
            val right = left + view.getWidth()
            //如果点击区域在输入框的区域内，忽略，不收起键盘
            return !(event.x > left && event.x < right && event.y > top && event.y < bottom)
        }
        return false
    }

    /**
     * 收起输入法
     *
     * @param token
     */
    private fun hideKeyboard(token: IBinder?) {
        if (token != null) {
            val im = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
            im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS)
        }
    }
}